import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import axios from 'axios';
// 创建一个 axios 实例
const service: AxiosInstance = axios.create({
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json;charset=utf-8',
        'X-Token': 'e8274125837e9dd5'
    },
})

// 请求池 + loading 状态管理
class RequestPool {
    private pool: Set<string> = new Set();
    private loading = false;
    private observers: ((loading: boolean) => void)[] = [];

    // 注册观察者
    observe(callback: (loading: boolean) => void): () => void {
        this.observers.push(callback);
        return () => {
            this.observers = this.observers.filter((cb) => cb !== callback);
        }
    }

    // 通知所有观察者
    private notify(loading: boolean): void {
        this.loading = loading;
        this.observers.forEach((callback) => callback(loading));
    }

    add(config: AxiosRequestConfig): void {
        const key = this.generateKey(config);
        if (!this.pool.has(key)) {
            this.pool.add(key);
            this.notify(true);
        }
    }

    remove(config: AxiosRequestConfig): void {
        const key = this.generateKey(config);
        if (this.pool.has(key)) {
            this.pool.delete(key);
            if (this.pool.size === 0) {
                this.notify(false);
            }
        }
    }

    private generateKey(config: AxiosRequestConfig): string {
        return `${config.method?.toUpperCase() || ''}:${config.url}`;
    }
}

const requestPool = new RequestPool()

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        requestPool.add(config);
        const token = sessionStorage.getItem('APP_PERMISSION') || localStorage.getItem('APP_PERMISSION')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    (error) => {
        if (error.config) {
            requestPool.remove(error.config);
        }
        return Promise.reject(error);
    },
)

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        requestPool.remove(response.config)
        return response
    },
    (error) => {
        requestPool.remove(error.config)
        const { response } = error
        if (response) {
            switch (response.status) {
                case 401:
                    // 未授权
                    // authenticationExpires()
                    console.warn('未授权，身份验证过期，请重新登陆！')
                    break
                case 404:
                    // 接口不存在
                    console.error('错误请求，接口不存在~')
                    break
                default:
                    break
            }
        }
        return response;
    },
);

// 设置最大并发数（示例：5）
// service.defaults.maxConcurrency = 5;

// 向外暴露 loading 状态观察器
export const onLoadingChange = (callback: (loading: boolean) => void) => {
    return requestPool.observe(callback);
};

export default service
